package com.hzf.wxplatform.web.controller.manager.pay;

import com.hzf.api.rpc.api.ApiService;
import com.hzf.common.base.BaseController;
import com.hzf.common.util.ByteUtils;
import com.hzf.common.util.CommonUtil;
import com.hzf.designer.dao.model.DneedsBidExample;
import com.hzf.designer.dao.model.DneedsDemand;
import com.hzf.designer.dao.model.DneedsDemandExample;
import com.hzf.material.dao.model.MaterialGoods;
import com.hzf.material.dao.model.MaterialGoodsExample;
import com.hzf.order.dao.model.*;
import com.hzf.ucenter.dao.model.UcenterUser;
import com.hzf.wxplatform.common.utils.UcenterUserUtils;
import com.jpay.ext.kit.HttpKit;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApiConfigKit;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.Document;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

/**
 * describe: TODO
 * creat_user: 白开水
 * creat_time: 2017/12/11   17:13
 **/
@Controller
@RequestMapping("/pay")
public class UserPayController extends BaseController {
    @Autowired
    ApiService apiService;
    @RequestMapping(value = "/orderNotify",method = RequestMethod.POST)
    @ResponseBody

    public void pay_notify(PrintWriter out, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取所有的参数
        Document resDoc = null;
        StringBuffer sbf=new StringBuffer();
        Enumeration<String> en=request.getParameterNames();
        while (en.hasMoreElements()) {
            Object o= en.nextElement();
            sbf.append(o.toString()+"="+request.getParameter(o.toString()));
        }


        // 支付结果通用通知文档: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7

        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);

//		String appid  = params.get("appid");

//		//商户号

//		String mch_id  = params.get("mch_id");

        String result_code  = params.get("result_code");
//		String openId      = params.get("openid");

//		//交易类型

//		String trade_type      = params.get("trade_type");

//		//付款银行

//		String bank_type      = params.get("bank_type");

//		// 总金额

//     	String total_fee     = params.get("total_fee");

//		//现金支付金额

//		String cash_fee     = params.get("cash_fee");

//		// 微信支付订单号

    	String transaction_id      = params.get("transaction_id");

//		// 商户订单号

		String out_trade_no      = params.get("out_trade_no");

//		// 支付完成时间，格式为yyyyMMddHHmmss

//		String time_end      = params.get("time_end");


        /////////////////////////////以下是附加参数///////////////////////////////////


        String attach      = params.get("attach");
//		String fee_type      = params.get("fee_type");

//		String is_subscribe      = params.get("is_subscribe");

//		String err_code      = params.get("err_code");

//		String err_code_des      = params.get("err_code_des");



        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态

        // 避免已经成功、关闭、退款的订单被再次更新

//		Order order = Order.dao.getOrderByTransactionId(transaction_id);

//		if (order==null) {
        //更新订单信息
        OrderUserExample example = new OrderUserExample();
        example.createCriteria().andIdEqualTo(Integer.parseInt(out_trade_no));
        OrderUser orderUser = apiService.selectOrder(example);
        if(orderUser.getPayState()==0){
        if(PaymentKit.verifyNotify(params, "EYZHrw8oTEnJFTAXDqPt6Onjg8umV2mR")){
            if (("SUCCESS").equals(result_code)) {


                    orderUser.setPayState(1);
                    orderUser.setPayTime(new Date());
                    orderUser.setOrderPayId(transaction_id);
                    apiService.updateOrder(orderUser);
                    if(orderUser.getOrderState()==0){
                        OrderUserInfoExample example1 = new OrderUserInfoExample();
                        example1.createCriteria().andOrderUserIdEqualTo(orderUser.getId());
                        List<OrderUserInfo> list = apiService.selectOrderInfoList(example1);
                        if(null!=list){
                            for(OrderUserInfo orderUserinfo:list){

                                orderUserinfo.setPayState(1);
                                orderUserinfo.setPayTime(System.currentTimeMillis());
                                apiService.updateOrderInfo(orderUserinfo);
                            }
                        }
                    }
                else if(orderUser.getOrderState()==1){
                        OrderUserDemandExample orderUserDemandExample =  new OrderUserDemandExample();
                        orderUserDemandExample.createCriteria().andOrderUserIdEqualTo(orderUser.getId());
                        OrderUserDemand orderUserDemand = apiService.getOrderUserDemand(orderUserDemandExample);
                        orderUserDemand.setPayState(1);
                        orderUserDemand.setPayTime(System.currentTimeMillis());
                        apiService.updateOrderUserDemand(orderUserDemand);
                        DneedsDemandExample dneedsDemandExample = new DneedsDemandExample();
                        dneedsDemandExample.createCriteria().andIdEqualTo(orderUserDemand.getDemandId());
                        DneedsDemand dneedsDemand  = apiService.getDneedsDemand(dneedsDemandExample);
                        dneedsDemand.setDemandType(3);
                        apiService.updateDneedsDemand(dneedsDemand);
                    }


                }
        }else{
                System.out.println(orderUser.getPayPrice());

                //发送通知等


                Map<String, String> xml = new HashMap<String, String>();
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                System.out.println(xml.toString());
                out.write(returnXML("SUCCESS"));
                return ;

            }
        }
//		}
        return ;
    }
    private String returnXML(String return_code) {

        return "<xml><return_code><![CDATA["

                + return_code

                + "]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }
}
